package com.zhuiyun.educations.api.video.conmtroller;

import cn.hutool.core.io.FileUtil;
import com.zhuiyun.educations.api.video.entity.FileMerge;
import com.zhuiyun.educations.api.video.mapper.VideoMapper;
import com.zhuiyun.educations.api.video.service.VideoService;
import com.zhuiyun.educations.common.errorCode.CommonException;
import com.zhuiyun.educations.common.response.CommonResult;
import com.zhuiyun.educations.util.pageUtil.PageRequest;
import com.zhuiyun.educations.util.pageUtil.PageResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName videoController
 * @Description TODO
 * @Author 杨友朋
 * @Date 2023/7/7 9:38
 **/
@RequestMapping("/video")
@CrossOrigin
@RestController
public class VideoController {
    @Resource
    VideoService videoService;

    /**
    * @Author 杨友朋
    * @Description TODO 分页全查
    * @Date 2023/7/7 15:07
    * @Return
    * @param pageRequest
    */
    @GetMapping("/selectVideo")
    public CommonResult selectVideo(PageRequest pageRequest){
        return CommonResult.ok(videoService.selectVideo(pageRequest));
    }
    @GetMapping("/selectById")
    public CommonResult selectById(Integer id){
        return CommonResult.ok(videoService.selectById(id));
    }
    /**
    * @Author 杨友朋
    * @Description TODO 全查
    * @Date 2023/7/7 15:08
    * @Return
    * @param
    */
    @GetMapping("/selectAll")
    public CommonResult selectAll(){
        return CommonResult.ok(videoService.selectAll());
    }

    /**
     * 根据id获取视频
     * @param response
     * @param id
     */
    @GetMapping("/getVideoById")
    public void getVideoById(HttpServletResponse response, Integer id) throws CommonException, FileNotFoundException {

       videoService.getVideoById(response,id);
    }

    @Resource
    VideoMapper videoMapper;
    @GetMapping("/getVideo")
    public void download(Integer id, HttpServletResponse response) throws IOException {
        FileMerge fileMerge = videoMapper.selectById(id);

        //根据文件的唯一标识码获取文件
        File uploadFile = new File(fileMerge.getFilePath());
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileMerge.getFilename(),"UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
